package com.zbkj.dal.common.utils;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * @author tianzhonghai
 * 2023/11/1 08:34
 */
public class PageInfoUtil {
    /**
     * PageInfo转换，性能高
     * @param source
     * @param convert
     * @return
     * @param <S>
     * @param <D>
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static  <S, D> PageInfo<D> convert(PageInfo<S> source, Function<S, D> convert) {
        if (source == null) {
            return new PageInfo<>();
        }

        PageInfo<D> destination = new PageInfo<>();
        destination.setList(Lists.newArrayList());

        List<D> ds = source.getList().stream().map(d -> {
                    return convert.apply(d);
                }
        ).collect(Collectors.toList());

        destination.getList().addAll(ds);

        destination.setTotal(source.getTotal());
        return destination;
    }

    /**
     * PageInfo转换，使用方便
     * @param source
     * @param destClass
     * @return
     * @param <S>
     * @param <D>
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <S, D> PageInfo<D> convert(PageInfo<S> source,Class<D> destClass) throws InstantiationException, IllegalAccessException {
        if (source == null) {
            return new PageInfo<>();
        }

        PageInfo<D> destination = new PageInfo<>();
        destination.setList(Lists.newArrayList());
        for (S s : source.getList()) {
//            D d = (D) destClass.newInstance();
            D d = BeanUtils.instantiateClass(destClass);
            BeanUtils.copyProperties(s, d);
            destination.getList().add(d);
        }
        destination.setTotal(source.getTotal());
        return destination;
    }
}
